package com.itHsuSE.demo8;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author Hsu琛君珩
 * @ClassName:Login
 * @date 2023-12-19
 * @apiNote
 * @Version: v1.0
 */

public class Login {
    public static void main(String[] args) {
        JFrame jf = new JFrame("登录");
        jf.setLayout((new FlowLayout(FlowLayout.LEFT)));
        jf.setBounds(400, 300, 300, 400);

        JLabel label1=new JLabel("账号：");
        //账号框，默认值是空，长度20
        JTextField usernameText=new JTextField("",20);
        JLabel label2=new JLabel("密码：");
        //密码框，默认值是空，长度20
        JPasswordField passwordText=new JPasswordField("",20);
        //状态框，默认值是登录状态，长度20
        JTextField out=new JTextField("登录状态",20);
        JButton button=new JButton("登录");

        jf.setResizable(false);//是否可调节大小：否
        button.setSize(40,20);

        jf.add(label1);
        jf.add(usernameText);
        jf.add(label2);
        jf.add(passwordText);
        jf.add(out);
        jf.add(button);

        button.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username=usernameText.getText();
                String password=passwordText.getText();
                try {
                    Connection connection = DBUtil.getConnection();
                    Statement statement=connection.createStatement();
                    ResultSet resultSet = statement.executeQuery("select * from user");
                    int flag=0;
                    while(resultSet.next()){
                        if(resultSet.getString(1).equals(username)
                         &&resultSet.getString(2).equals(password)){
                            flag=1;
                            out.setText("登录成功");
                        }
                    }
                    if(flag==0){
                        out.setText("登录失败");
                    }
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }finally {
                    try {
                        DBUtil.close();
                    } catch (SQLException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        });

        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
